import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag, Switch } from 'tdesign-react';
import { SearchIcon, AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { JupiterRole, JupiterRoleQuery, JupiterPermission, JupiterRolePermisson } from '../../types/roleTypes';
import { formatTime } from '../../utils/timeutil';
import {
    fetchRoleList,
    createRole,
    updateRole,
    deleteRole,
    restoreRole,
    getPermissionTreeService,
    getRolePermissionsService,
    updateRolePermissionsService
} from '../../services/roleService';
import RoleForm from './components/RoleForm';
import RolePermissionForm from './components/RolePermissionForm';

export default function RolePage() {
    const [roleList, setRoleList] = useState<JupiterRole[]>([]);
    const [loading, setLoading] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [formPermissionVisible, setFormPermissionVisible] = useState(false);
    const [editingRole, setEditingRole] = useState<Partial<JupiterRole>>();
    const [permissionTree, setPermissionTree] = useState<JupiterPermission[]>();
    const [rolePermissionIds, setRolePermissionIds] = useState<string[]>();
    const [title, setTitle] = useState('新增角色');

    // 搜索条件
    const [searchRoleName, setSearchRoleName] = useState('');

    // 分页
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const getList = async () => {
        setLoading(true);
        try {
            const params: JupiterRoleQuery = {
                name: searchRoleName || undefined,
                page: pagination.current,
                size: pagination.pageSize,
            };
            const res = await fetchRoleList(params);
            if (res.code === 200) {
                setRoleList(res.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    total: res.data.total || 0,
                }));
            }
        } catch (e) {
            console.error('请求异常:', e);
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = () => {
        setEditingRole(undefined);
        setTitle('新增角色');
        setFormVisible(true);
    };

    const handleEdit = (record: JupiterRole) => {
        setEditingRole(record);
        setTitle('编辑角色');
        setFormVisible(true);
    };

    const getPermissionTree = async () => {
        try {
            const res = await getPermissionTreeService();
            if (res.code === 200) {
                setPermissionTree(res.data || []);
            }
        } catch (e) {
            console.error('请求异常:', e);
        }
    };

    const getRolePermissions = async (record: JupiterRole) => {
        try {
            const res = await getRolePermissionsService(record.uuid);
            if (res.code === 200) {
                setRolePermissionIds(res.data || []);
            }
        } catch (e) {
            console.error('请求异常:', e);
        }
    };

    const handlePermissionEdit = (record: JupiterRole) => {
        getPermissionTree()
        getRolePermissions(record)
        setEditingRole(record);
        setFormPermissionVisible(true);
    };

    const handleRolePermissionSubmit = async (data: Partial<JupiterRolePermisson>) => {
        try {
            await updateRolePermissionsService(data);
            MessagePlugin.success('更新成功');
            setFormPermissionVisible(false);
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handleDelete = (record: JupiterRole) => {
        const confirmDialog = DialogPlugin.confirm({
            header: '删除确认',
            closeOnOverlayClick: false,
            body: `确定删除角色【${record.name}】？`,
            //closeBtn: false, // 不显示右上角关闭按钮
            onConfirm: async () => {
                try {
                    await deleteRole(record.uuid);
                    MessagePlugin.success('删除成功');
                    getList();
                    confirmDialog.hide();
                } catch (error) {
                    MessagePlugin.error('删除失败');
                }
            },
            onCancel: () => {
                confirmDialog.hide(); // 取消时手动关闭
            },
            onClose: () => {
                confirmDialog.hide(); // 右上角叉号关闭
            },
        });
    };

    const handleRestore = (record: JupiterRole) => {
        const confirmDialog = DialogPlugin.confirm({
            header: '恢复确认',
            body: `确定恢复权限【${record.name}】？`,
            onConfirm: async () => {
                await restoreRole(record.uuid);
                MessagePlugin.success('恢复成功');
                getList();
                confirmDialog.hide();
            },
            onCancel: () => {
                confirmDialog.hide(); // 取消时手动关闭
            },
            onClose: () => {
                confirmDialog.hide(); // 右上角叉号关闭
            },
        });
    };

    const handleSubmit = async (data: Partial<JupiterRole>) => {
        try {
            if (editingRole?.uuid) {
                await updateRole(editingRole.uuid, data);
                MessagePlugin.success('更新成功');
            } else {
                await createRole(data);
                MessagePlugin.success('创建成功');
            }
            setFormVisible(false);
            getList();
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleReset = () => {
        setSearchRoleName('');
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handlePageChange = (pageInfo: any) => {
        setPagination(prev => ({
            ...prev,
            current: pageInfo.current,
            pageSize: pageInfo.pageSize,
        }));
        getList();
    };

    useEffect(() => {
        getList();
    }, [pagination.current, pagination.pageSize]);


    return (
        <Card title="角色管理">
            {/* 搜索区域 */}
            <div style={{ marginBottom: 16, padding: '16px 0', borderBottom: '1px solid #e7e7e7' }}>
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    <Input
                        placeholder="角色名称"
                        value={searchRoleName}
                        onChange={(value) => setSearchRoleName(value as string)}
                        style={{ width: 200 }}
                    />
                    <Button theme="primary" icon={<SearchIcon />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button theme="default" onClick={handleReset}>
                        重置
                    </Button>
                </div>
            </div>

            {/* 操作按钮 */}
            <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
                    新增角色
                </Button>
            </div>

            {/* 表格 */}
            <Table
                data={roleList}
                rowKey="uuid"
                loading={loading}
                pagination={pagination}
                onPageChange={handlePageChange}
                columns={[
                    { colKey: 'name', title: '角色名称', width: 150 },
                    { colKey: 'description', title: '描述', width: 200 },
                    { colKey: 'createTime', title: '创建时间', width: 180, cell: ({ row }) => formatTime(row.createTime || ""), },
                    { colKey: 'updateTime', title: '更新时间', width: 180, cell: ({ row }) => formatTime(row.updateTime || ""), },
                    {
                        colKey: 'delete_status',
                        title: '删除状态',
                        width: 100,
                        cell: ({ row }) => (
                            <Tag theme={row.deleteTime ? 'danger' : 'success'}>
                                {row.deleteTime ? '已删除' : '正常'}
                            </Tag>
                        ),
                    },
                    {
                        colKey: 'operation',
                        title: '操作',
                        width: 200,
                        cell: ({ row }) => (
                            <>
                                {row.deleteTime === null ? (
                                    <>
                                        <Button
                                            theme="primary"
                                            variant="text"
                                            icon={<EditIcon />}
                                            onClick={() => handleEdit(row)}
                                        >
                                            编辑
                                        </Button>
                                        <Button
                                            theme="primary"
                                            variant="text"
                                            icon={<EditIcon />}
                                            onClick={() => handlePermissionEdit(row)}
                                        >
                                            编辑权限
                                        </Button>
                                        <Button
                                            theme="danger"
                                            variant="text"
                                            icon={<DeleteIcon />}
                                            onClick={() => handleDelete(row)}
                                        >
                                            删除
                                        </Button>
                                    </>
                                ) : (
                                    <Button
                                        theme="success"
                                        variant="text"
                                        icon={<RefreshIcon />}
                                        onClick={() => handleRestore(row)}
                                    >
                                        恢复
                                    </Button>
                                )}
                            </>
                        ),
                    }
                ]}
            />

            {/* 表单弹窗 */}
            <RoleForm
                visible={formVisible}
                onClose={() => setFormVisible(false)}
                onSubmit={handleSubmit}
                initialData={editingRole}
                title={title}
            />
            <RolePermissionForm
                visible={formPermissionVisible}
                onClose={() => setFormPermissionVisible(false)}
                onSubmit={handleRolePermissionSubmit}
                initialData={editingRole}
                permissionTree={permissionTree || []}
                permissionIds={rolePermissionIds || []}
                title="编辑权限"
            />
        </Card>
    );
}
